package hook

import (
	"encoding/json"
	"time"

	"gitee.com/xgotool/backend-framework-template/config"
	"gitee.com/xgotool/backend-framework-template/model"
	"gitee.com/xiaoyutab/xgotool/xstring"
)

// 用户创建钩子
//
//	hook.user.create	<model.User>
func UserCreate(param []byte) error {
	mod := model.User{}
	err := json.Unmarshal(param, &mod)
	if err != nil {
		return err
	}
	conn, err := config.GetConnect()
	if err != nil {
		return err
	}
	// 检测用户钱包是否存在
	old := model.Wallet{}
	conn.Table(old.TableName()).Where("uid", mod.Id).Limit(1).Find(&old)
	if old.Id == 0 {
		// 添加完用户以后，给用户添加对应的默认钱包信息
		wallet := model.Wallet{
			Uid:       mod.Id,
			UpdatedAt: time.Now().Unix(),
		}
		conn.Table(wallet.TableName()).Create(&wallet)
		// 添加钱包相关开户日志
		wallet_log := model.WalletLog{
			WalletId:  wallet.Id,
			Type:      1,
			OrderNo:   xstring.RandomNo("WT", 3),
			Note:      "钱包开户",
			CreatedAt: time.Now().Unix(),
		}
		conn.Table(wallet_log.TableName()).Create(&wallet_log)
	}
	return nil
}
